package com.zhao.newcoder.controller;

import com.zhao.newcoder.DTO.User;
import com.zhao.newcoder.DTO.response.TokenInfo;
import com.zhao.newcoder.DTO.response.UserResponse;
import com.zhao.newcoder.Soup.Result;
import com.zhao.newcoder.Soup.ResultCode;
import com.zhao.newcoder.controller.base.BaseController;
import com.zhao.newcoder.exception.CommonException;
import com.zhao.newcoder.service.UserService;
import io.netty.handler.codec.Headers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;

/**
 * TODO
 * user类controller 暂时其中没有什么接口和逻辑
 *
 * @author: ZhouBin
 * @date: 2020/10/9 9:15 上午
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/user")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class UserController extends BaseController {
    private final UserService userService;
    private RestTemplate restTemplate = new RestTemplate();

    @GetMapping(value = "/{id}")
    public Result<UserResponse> findById(@PathVariable String id) throws CommonException {
        User user = userService.findById(id);
        UserResponse userResponse = user.buildUserResponse();

        UserResponse user1 = (UserResponse) request.getSession().getAttribute("user");
//        if(user1 == null || !StringUtils.equals(user1.getId(),id)){
//            throw new CommonException(new Result(ResultCode.UNAUTHENTICATED));
//        }
        return new Result<UserResponse>(ResultCode.SUCCESS,user1);
    }

    /***
     * TODO
     * 登录接口，目前登录通过basic方式，在请求头中 Authorization 带userId、password的信息
     * 认证方式后面需要更换
     *
     * @author: ZhouBin
     * @date: 2020/10/9 8:02 下午
     * @param userResponse
     * @return void
     */
    @PostMapping(value = "/login")
    public Result<TokenInfo> login(@Validated @RequestBody UserResponse userResponse){
        UserResponse response = userService.login(userResponse);
        HttpSession session = request.getSession(false);
        if(session!=null){
            session.invalidate();
        }
//        request.getSession(true).setAttribute("user",response);

        log.info("username:{},password:{}",response.getPhoneNumber(),response.getPassword());
        String oauthServiceUrl = "https://pa.kobefan.cn/oauth/token";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setBasicAuth("gateway", "123456");

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("username", response.getPhoneNumber());
        params.add("password", response.getPassword());
        params.add("grant_type", "password");
        params.add("scope", "read write");

        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);

        ResponseEntity<TokenInfo> responseEntity = restTemplate.postForEntity(oauthServiceUrl, entity, TokenInfo.class);
        TokenInfo newToken = responseEntity.getBody().init();

        if(newToken!=null){
            request.getSession().setAttribute("token",newToken);
            return new Result<TokenInfo>(ResultCode.SUCCESS,newToken);
        }
        return new Result<>(ResultCode.MOBILE_OR_PASSWORD_ERROR);

    }

    /**
     * TODO
     * 退出接口
     *
     * @author: ZhouBin
     * @date: 2020/10/9 8:02 下午
     * @param
     * @return void
     */
    @PostMapping(value = "/loginOut")
    public void loginOut(){
        request.getSession().invalidate();
    }
}
    